package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public List<Address> findList() {
        //查询当前用户的地址列表
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        return addressMapper.selectList(wrapper);
    }

    @Override
    public void addAddress(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);//非默认值
        addressMapper.insert(address);
    }

    @Override
    public void setDefault(Long id) {
        //1. 将当前用户的所有地址设置为非默认0
        Address address = new Address();
        address.setIsDefault(0);
        //2.设置更新条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        addressMapper.update(address, wrapper);
        //3.将当前id设为默认地址
        //update address_book set is_default = 1 where id = #{前端传入的id}
        address.setIsDefault(1);
        address.setId(id);
        addressMapper.updateById(address);

    }

    @Override
    public Address findDefault() {
        //查询当前用户is_default=1的记录
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId())
                .eq(Address::getIsDefault, 1);
        return addressMapper.selectOne(wrapper);
    }

    @Override
    public Address findById(Long id) {
        //通过用户id回显地址id
        // select * from address_book where id = #{id}
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getId, id);
        return addressMapper.selectOne(wrapper);
    }

    @Override
    public void save(Address address) {
        addressMapper.updateById(address);
    }

    @Override
    public void deleteByIds(Long ids) {

        addressMapper.deleteById(ids);
    }
}